﻿using System;
using System.Text.RegularExpressions;

namespace Zipun.VkOnlineMusic.Api.Domain
{
    public class VkToken
    {
        private const string AuthPageString = "http://oauth.vk.com/authorize";
        private const string ClientIdString = "3035290";
        private const string AppScopeString = "audio";
        private const string DisplayTypeString = "popup";
        public const string RedirectUriString = "http://oauth.vk.com/blank.html";
        public const string LoginUrlString = AuthPageString + 
                                             "?client_id=" + ClientIdString +
                                             "&scope=" + AppScopeString +
                                             "&redirect_uri=" + RedirectUriString +
                                             "&display=" + DisplayTypeString + 
                                             "&response_type=token";

        private const string TokenStringRegexpPattern = RedirectUriString + 
                                                        "#access_token=([0-9a-f]+)" +
                                                        "&expires_in=(\\d+)" +
                                                        "&user_id=(\\d+)";

        public VkToken(string tokenString)
        {
            var tokenRegex = new Regex(TokenStringRegexpPattern);
            var match = tokenRegex.Match(tokenString);
            if (!match.Success)
            {
                // TODO create my own exceptions
                // TODO analyse token string
                throw new Exception("Wrong token string");
            }
            AccessToken = match.Groups[1].Value;
            ExpiresIn = DateTime.Now.AddSeconds(Convert.ToDouble(match.Groups[2].Value));
            UserId = Convert.ToInt32(match.Groups[3].Value);
        }

        public int UserId { get; private set; }
        public DateTime ExpiresIn { get; private set; }
        public string AccessToken { get; private set; }
    }
}